{% extends "base.html" %}

{% block content %}
<div class="d-flex justify-content-between align-items-center mb-4">
    <h1 class="h3 mb-0 text-gray-800">Package Management</h1>
    <a href="{{ url_for('index') }}" class="btn btn-secondary">
        <i class="bi bi-arrow-left me-1"></i> Back to Dashboard
    </a>
</div>

<!-- 简化的任务状态显示 -->
<div id="taskStatusArea" class="d-none">
    <div class="card shadow mb-4">
        <div class="card-header py-3">
            <h6 class="m-0 font-weight-bold text-primary">Task Status</h6>
        </div>
        <div class="card-body">
            <div id="currentTaskStatus" class="mb-3"></div>
            <div id="taskOutput" class="bg-light p-3 rounded" style="max-height: 150px; overflow-y: auto; font-family: monospace; font-size: 0.9em;"></div>
        </div>
    </div>
</div>

<div class="row">
    <div class="col-lg-8">
        <div class="card shadow mb-4">
            <div class="card-header py-3">
                <h6 class="m-0 font-weight-bold text-primary">Install Python Packages</h6>
            </div>
            <div class="card-body">
                <form id="packageForm">
                    <div class="mb-3">
                        <label for="packageInput" class="form-label">Package Name or Pip Command</label>
                        <div class="input-group">
                            <input type="text" class="form-control" id="packageInput"
                                   placeholder="Package name or pip command (e.g., 'requests' or 'pip install requests')">
                            <button type="submit" class="btn btn-primary" id="installBtn">
                                <i class="bi bi-download me-1"></i> Install
                            </button>
                        </div>
                        <div class="form-text">
                            Enter a package name (e.g., "requests") or full pip command (e.g., "pip install requests==2.25.1")
                        </div>
                    </div>

                    <!-- 包源配置 -->
                    <div class="mb-3">
                        <label for="packageSource" class="form-label">Package Source (Optional)</label>
                        <div class="input-group">
                            <select class="form-select" id="packageSourceSelect">
                                <option value="">Default (PyPI)</option>
                                <option value="https://pypi.tuna.tsinghua.edu.cn/simple">Tsinghua University</option>
                                <option value="https://mirrors.aliyun.com/pypi/simple/">Aliyun</option>
                                <option value="https://pypi.douban.com/simple/">Douban</option>
                                <option value="https://pypi.mirrors.ustc.edu.cn/simple/">USTC</option>
                                <option value="custom">Custom Source</option>
                            </select>
                            <input type="text" class="form-control d-none" id="customPackageSource"
                                   placeholder="Enter custom package source URL">
                        </div>
                        <div class="form-text">
                            Select a package source mirror or enter a custom URL to speed up downloads
                        </div>
                    </div>

                    <!-- 安装选项 -->
                    <div class="mb-3">
                        <div class="form-check">
                            <input class="form-check-input" type="checkbox" id="noDepsCheckbox">
                            <label class="form-check-label" for="noDepsCheckbox">
                                Install without dependencies (--no-deps)
                            </label>
                        </div>
                        <div class="form-check">
                            <input class="form-check-input" type="checkbox" id="noCacheDirCheckbox">
                            <label class="form-check-label" for="noCacheDirCheckbox">
                                Disable cache (--no-cache-dir)
                            </label>
                        </div>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <div class="col-lg-4">
        <div class="card shadow">
            <div class="card-header py-3 d-flex justify-content-between align-items-center">
                <h6 class="m-0 font-weight-bold text-primary">Installed Packages</h6>
                <button class="btn btn-sm btn-outline-secondary" onclick="loadInstalledPackages()" id="refreshBtn">
                    <i class="bi bi-arrow-clockwise"></i> Refresh
                </button>
            </div>
            <div class="card-body">
                <div class="table-responsive">
                    <table class="table table-sm">
                        <thead>
                            <tr>
                                <th>Package</th>
                                <th>Version</th>
                                <th>Actions</th>
                            </tr>
                        </thead>
                        <tbody id="installedPackages">
                            <tr>
                                <td colspan="3" class="text-center">Loading packages...</td>
                            </tr>
                        </tbody>
                    </table>
                </div>

                <div class="mt-3">
                    <button class="btn btn-sm btn-outline-danger" onclick="uninstallAllPackages()" id="uninstallAllBtn">
                        <i class="bi bi-trash me-1"></i> Uninstall All Packages
                    </button>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- 确认卸载模态框 -->
<div class="modal fade" id="confirmUninstallModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Confirm Uninstall</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <p>Are you sure you want to uninstall <span id="packageNameToUninstall"></span>?</p>
                <p class="text-danger">This action cannot be undone.</p>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                <button type="button" class="btn btn-danger" id="confirmUninstallBtn">Uninstall</button>
            </div>
        </div>
    </div>
</div>

<!-- 确认全部卸载模态框 -->
<div class="modal fade" id="confirmUninstallAllModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Confirm Uninstall All Packages</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <p>Are you sure you want to uninstall ALL packages?</p>
                <p class="text-danger">This action cannot be undone and may break your APIs.</p>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                <button type="button" class="btn btn-danger" onclick="confirmUninstallAll()">Uninstall All</button>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block scripts %}
<script>
// 全局变量来跟踪当前任务
let currentTaskId = null;

document.addEventListener('DOMContentLoaded', function() {
    // 加载已安装的包
    loadInstalledPackages();

    // 包安装表单提交
    const packageForm = document.getElementById('packageForm');
    if (packageForm) {
        packageForm.addEventListener('submit', function(e) {
            e.preventDefault();
            installPackage();
        });
    }

    // 设置确认卸载按钮的事件
    document.getElementById('confirmUninstallBtn').addEventListener('click', function() {
        const packageName = this.dataset.packageName;
        if (packageName) {
            performUninstall(packageName);
        }
        var modal = bootstrap.Modal.getInstance(document.getElementById('confirmUninstallModal'));
        modal.hide();
    });

    // 包源选择事件处理
    const sourceSelect = document.getElementById('packageSourceSelect');
    const customSourceInput = document.getElementById('customPackageSource');

    sourceSelect.addEventListener('change', function() {
        if (this.value === 'custom') {
            customSourceInput.classList.remove('d-none');
            customSourceInput.focus();
        } else {
            customSourceInput.classList.add('d-none');
            customSourceInput.value = '';
        }
    });
});

function setButtonsState(disabled) {
    document.getElementById('installBtn').disabled = disabled;
    document.getElementById('refreshBtn').disabled = disabled;
    document.getElementById('uninstallAllBtn').disabled = disabled;

    // 禁用所有卸载按钮
    document.querySelectorAll('#installedPackages button').forEach(btn => {
        btn.disabled = disabled;
    });
}

function showTaskStatus(taskType, taskId) {
    currentTaskId = taskId;
    document.getElementById('taskStatusArea').classList.remove('d-none');
    document.getElementById('taskOutput').innerHTML = 'Task started...';

    // 根据任务类型设置状态信息
    const statusText = taskType === 'install' ? 'Installing package...' : 'Uninstalling package...';
    document.getElementById('currentTaskStatus').innerHTML = `
        <div class="d-flex justify-content-between align-items-center">
            <span>${statusText}</span>
            <span class="badge bg-primary">Running</span>
        </div>
    `;

    // 禁用按钮
    setButtonsState(true);

    // 简化的状态检查 - 只检查一次，然后依赖自动刷新
    setTimeout(() => {
        checkTaskStatus(taskType, taskId);
    }, 3000);
}

function checkTaskStatus(taskType, taskId) {
    const statusEndpoint = taskType === 'install' ? '/api/installation_status/' : '/api/uninstallation_status/';

    axios.get(statusEndpoint + taskId)
    .then(response => {
        const task = response.data;

        // 更新输出
        const taskOutput = document.getElementById('taskOutput');
        let outputContent = '';
        if (task.output) {
            outputContent += task.output + '\n';
        }
        if (task.error) {
            outputContent += 'ERROR: ' + task.error + '\n';
        }
        taskOutput.innerHTML = outputContent;
        taskOutput.scrollTop = taskOutput.scrollHeight;

        if (task.status === 'completed') {
            if (task.success) {
                document.getElementById('currentTaskStatus').innerHTML = `
                    <div class="d-flex justify-content-between align-items-center">
                        <span>Task completed successfully!</span>
                        <span class="badge bg-success">Completed</span>
                    </div>
                `;
            } else {
                document.getElementById('currentTaskStatus').innerHTML = `
                    <div class="d-flex justify-content-between align-items-center">
                        <span>Task failed!</span>
                        <span class="badge bg-danger">Failed</span>
                    </div>
                `;
            }

            // 任务完成，重新启用按钮并刷新包列表
            setTimeout(() => {
                setButtonsState(false);
                loadInstalledPackages();

                // 3秒后隐藏状态区域
                setTimeout(() => {
                    document.getElementById('taskStatusArea').classList.add('d-none');
                }, 3000);
            }, 1000);
        } else {
            // 如果任务还在运行，5秒后再检查一次
            setTimeout(() => {
                checkTaskStatus(taskType, taskId);
            }, 5000);
        }
    })
    .catch(error => {
        console.error('Error checking task status:', error);
        // 即使状态检查失败，我们也假设任务已完成并重新启用按钮
        document.getElementById('currentTaskStatus').innerHTML = `
            <div class="d-flex justify-content-between align-items-center">
                <span>Task completed (status check failed)</span>
                <span class="badge bg-warning">Completed</span>
            </div>
        `;

        setTimeout(() => {
            setButtonsState(false);
            loadInstalledPackages();

            // 3秒后隐藏状态区域
            setTimeout(() => {
                document.getElementById('taskStatusArea').classList.add('d-none');
            }, 3000);
        }, 1000);
    });
}

function getInstallOptions() {
    // 获取包源
    const sourceSelect = document.getElementById('packageSourceSelect');
    const customSourceInput = document.getElementById('customPackageSource');
    let packageSource = '';

    if (sourceSelect.value === 'custom' && customSourceInput.value.trim()) {
        packageSource = customSourceInput.value.trim();
    } else if (sourceSelect.value && sourceSelect.value !== 'custom') {
        packageSource = sourceSelect.value;
    }

    // 获取安装选项
    const noDeps = document.getElementById('noDepsCheckbox').checked;
    const noCacheDir = document.getElementById('noCacheDirCheckbox').checked;

    return {
        source: packageSource,
        no_deps: noDeps,
        no_cache_dir: noCacheDir
    };
}

function installPackage() {
    const packageInput = document.getElementById('packageInput');

    if (!packageInput.value.trim()) {
        alert('Please enter a package name or command');
        return;
    }

    const installOptions = getInstallOptions();

    axios.post('/api/install_package', {
        package: packageInput.value,
        options: installOptions
    })
    .then(response => {
        if (response.data.task_id) {
            packageInput.value = ''; // 清空输入框
            showTaskStatus('install', response.data.task_id);
            showNotification('Installation started successfully', 'info');
        } else {
            showNotification('Failed to start installation: ' + (response.data.error || 'Unknown error'), 'danger');
        }
    })
    .catch(error => {
        let errorMsg = 'Installation failed to start';
        if (error.response && error.response.data) {
            errorMsg = error.response.data.error || errorMsg;
        }
        showNotification(errorMsg, 'danger');
    });
}

function loadInstalledPackages() {
    const tableBody = document.getElementById('installedPackages');
    tableBody.innerHTML = '<tr><td colspan="3" class="text-center">Loading packages...</td></tr>';

    axios.get('/api/installed_packages')
    .then(response => {
        if (response.data.packages && response.data.packages.length > 0) {
            let html = '';
            response.data.packages.forEach(pkg => {
                html += `
                <tr>
                    <td>${escapeHtml(pkg.name)}</td>
                    <td>${escapeHtml(pkg.version)}</td>
                    <td>
                        <button class="btn btn-sm btn-danger" onclick="confirmUninstall('${escapeHtml(pkg.name)}')">
                            <i class="bi bi-trash"></i> Uninstall
                        </button>
                    </td>
                </tr>
                `;
            });
            tableBody.innerHTML = html;
        } else {
            tableBody.innerHTML = '<tr><td colspan="3" class="text-center">No packages found</td></tr>';
        }
    })
    .catch(error => {
        tableBody.innerHTML = '<tr><td colspan="3" class="text-center text-danger">Failed to load packages</td></tr>';
        console.error('Error loading packages:', error);
    });
}

function confirmUninstall(packageName) {
    document.getElementById('packageNameToUninstall').textContent = packageName;
    document.getElementById('confirmUninstallBtn').dataset.packageName = packageName;
     // 使用 Bootstrap 5 的模态框 API 替代 jQuery
    var modal = new bootstrap.Modal(document.getElementById('confirmUninstallModal'));
    modal.show();
}

function performUninstall(packageName) {
    axios.post('/api/uninstall_package', {
        package: packageName
    })
    .then(response => {
        if (response.data.task_id) {
            showTaskStatus('uninstall', response.data.task_id);
            showNotification('Uninstallation started successfully', 'info');
        } else {
            showNotification('Failed to start uninstallation: ' + (response.data.error || 'Unknown error'), 'danger');
        }
    })
    .catch(error => {
        showNotification(`Failed to start uninstallation: ${error.response?.data?.error || error.message}`, 'danger');
    });
}

function uninstallAllPackages() {
    var modal = new bootstrap.Modal(document.getElementById('confirmUninstallAllModal'));
    modal.show();
}

function confirmUninstallAll() {
    var modal = bootstrap.Modal.getInstance(document.getElementById('confirmUninstallAllModal'));
    modal.hide();

    // 获取所有包名
    const packages = [];
    document.querySelectorAll('#installedPackages tr').forEach(row => {
        const packageName = row.cells[0].textContent;
        if (packageName && packageName !== 'Loading packages...' && packageName !== 'No packages found') {
            packages.push(packageName);
        }
    });

    if (packages.length === 0) {
        showNotification('No packages to uninstall', 'info');
        return;
    }

    // 逐个卸载所有包
    let uninstalledCount = 0;
    const totalCount = packages.length;

    const uninstallNext = () => {
        if (packages.length === 0) {
            showNotification(`Uninstalled ${uninstalledCount} of ${totalCount} packages`, 'success');
            loadInstalledPackages();
            return;
        }

        const packageName = packages.shift();
        axios.post('/api/uninstall_package', {
            package: packageName
        })
        .then(response => {
            if (response.data.task_id) {
                uninstalledCount++;
                showNotification(`Started uninstalling ${packageName} (${uninstalledCount}/${totalCount})`, 'info');
            }
            uninstallNext();
        })
        .catch(error => {
            console.error(`Failed to start uninstallation for ${packageName}:`, error);
            uninstallNext();
        });
    };

    showNotification(`Starting to uninstall ${totalCount} packages...`, 'info');
    uninstallNext();
}

function showNotification(message, type) {
    // 简单的通知实现
    const alertClass = type === 'success' ? 'alert-success' :
                      type === 'danger' ? 'alert-danger' :
                      type === 'warning' ? 'alert-warning' : 'alert-info';
    
    const notification = document.createElement('div');
    notification.className = `alert ${alertClass} alert-dismissible fade show`;
    notification.innerHTML = `
        ${message}
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    `;
    
    // 添加到页面顶部
    document.querySelector('.main-content').prepend(notification);
    
    // 5秒后自动消失
    setTimeout(() => {
        if (notification.parentNode) {
            notification.remove();
        }
    }, 5000);
}

function escapeHtml(text) {
    const div = document.createElement('div');
    div.textContent = text;
    return div.innerHTML;
}
</script>
{% endblock %}